<?php
/**
 * created by zzy
 * date: 2017/10/24 9:28
 */

namespace App\Api\Service\User\Controllers;

use App\Eloquent\Ygt\UserMessage;
use Framework\BaseClass\Api\Controller;
use App\Eloquent\Ygt\User;
use App\Eloquent\Ygt\DepartmentUser;
use App\Eloquent\Ygt\UserToken;
use App\Eloquent\Ygt\UserTokenLog;
use App\Eloquent\Ygt\Sms;
use App\Eloquent\Ygt\Privilege;
use App\Eloquent\Ygt\Appnode;
use App\Engine\Func;
use Framework\Services\Push\JPush\JPushService;
use Framework\Services\SMS\Xinxiguanjia\ZhaoyongService;

class IndexController extends Controller
{

    //注册
    public function register()
    {
        $mobile             = request('mobile');
        $truename           = request('truename');
        $password           = request('password');
//        $code               = request('code');
        if( !$truename || !$password || !$mobile ){
            xThrow( ERR_PARAMETER );
        }

//        $codeResult        = Sms::checkCode( $mobile, $code );
//        if( !$codeResult ){
//            xThrow( 300001 );
//        }

        $salt               = mt_rand( 100000, 999999 );
        $password_md5       = User::passwordMd5( $password, $salt );
        $where              = ['mobile'=>$mobile];
        $info               = User::getInfo( $where );
        if( $info ){
           // $result     = '手机号码已存在';
            xThrow( MOBILE_EXIST );
        }

        $user_data          = [ 'mobile'=>$mobile, 'truename'=>$truename, 'password'=>$password_md5, 'salt'=>$salt ];
        $insertResult      = User::insertOneData( $user_data );
        if( !$insertResult ){
            //$result     = '注册失败';
            xThrow( ERR_UNKNOWN );
        }
        $result             = ['message'=>'注册成功'];
        return $result;
    }

    //登录
    public function login()
    {
//        header 值
//        userid			默认0
//        token			默认''
//        imei			手机唯一标识
//        appv			app的版本号
//        platform		android/ios
//        platformv		android/ios的版本号
        $mobile                 = request('mobile');
        $password               = request('password');

        $imei                   = Func::getHeaderValueByName( 'imei','xxxx' );
        $appv                   = Func::getHeaderValueByName( 'appv','1.0' );
        $platform               = Func::getHeaderValueByName( 'platform',1 );
        $platformv              = Func::getHeaderValueByName( 'platformv','1.11' );

        if( !$mobile || !$password ){
            xThrow( ERR_PARAMETER );
        } else {
            $where                  = [ 'mobile'=>$mobile ];
            $info                   = User::getLoginInfoNew( $where, $password );
            if( $info['status'] == true ){
                $user               = $info['user'];
                $userId            = $user['id'];
                $companyId         = $user['company_id'];
                if( !$companyId )
                {
                    xThrow( LOGIN_NO_COMPANY );
                }
                $departUser         = DepartmentUser::getCurrentInfo( $userId );
                $nodes              = $iosNodes = [];
                if( $departUser )
                {
                    $privilegeId        = $departUser->privilege_id;
                    $where              = ['id'=>$privilegeId];
                    $privilege          = Privilege::getInfo($where);
                    if($privilege){
                        $nowTime        = $_SERVER['REQUEST_TIME'];
                        $nowDay         = date('Y-m-d',$nowTime);
                        $startTimeH     = $privilege->login_start_time;
                        $endTimeH       = $privilege->login_end_time;
                        $startTimeDate  = $nowDay.' '.$startTimeH;
                        $endTimeDate    = $nowDay.' '.$endTimeH;
                        $startTime      = strtotime($startTimeDate);
                        $endTime        = strtotime($endTimeDate);
                        if($startTimeH!=0 && $startTime>$nowTime)
                        {
                            xThrow( ERR_UNKNOWN,'未到上班时间' );
                        }
                        if($endTimeH!=0 && $endTime<$nowTime)
                        {
                            xThrow( ERR_UNKNOWN,'已经下班了' );
                        }
                    }else{
                        if($companyId!=2)
                        {
                            xThrow( ERR_UNKNOWN );
                        }
                    }
                    $appnodeList        = Appnode::getList('')->toArray();
                    $privilegeAppnode   = Privilege::getAppnodeList( $privilegeId )->toArray();
                    foreach( $appnodeList as $key=>$val ){
                        $isShow        = 0;
                        foreach( $privilegeAppnode as $k=>$v ){
                            if( $val['id'] == $v['id'] && $v['id'] ){
                                $isShow        = 1;
                                $iosNodes[]    = $v['alias'];
                            }
                        }
                        $nodes[$val['alias']]   = $isShow;
                    }
                    $salt               = mt_rand( 100000,999999 );
                    $tokenData         = [
                        'user_id'=>$userId,'imei'=>$imei,'salt'=>$salt, 'is_login'=>1,
                        'app_version'=>$appv, 'platform'=>$platform, 'platform_version'=>$platformv
                    ];
                    UserToken::saveOneData( $tokenData );
                    array_pull($tokenData, 'is_login');
                    UserTokenLog::insertOneData($tokenData);
                    //app小红点数字
                    $where          = ['is_read'=>0,'to_user_id'=>$userId];
                    $messageCount   = UserMessage::getCount($where);
                    $iosArr         = ['badge'=>$messageCount];
                    $androidArr     = [];
                    $jpush          = new JPushService();
                    $jpush->sendByMobile( $mobile,'',$iosArr,$androidArr );

                    $token      = UserToken::tokenEncode($userId, $imei, $salt);
                    $token      = $token.$salt.$userId;

                    //库存管理-进去后上方的三个按钮
                    //0:材料   1:成品   2:废品   3:退品
                    //下单人[全有]--废品员[只有废品]-[其它角色]-只有前两个 --新增仓管员也能看到废品 zhuyujun 20180914
                    if(in_array('order_list_jump',$iosNodes) || in_array('stock_buttom_hide',$iosNodes)){
                        $stockButtonArr     = [0,4,1,2,3];//下单人权限&仓管员
                    }else if(in_array('waster',$iosNodes)){
                        $stockButtonArr     = [2];//废品员权限
                    }else if(in_array('purchasing_agent',$iosNodes)){
                        $stockButtonArr     = [0,3];//采购员权限
                    }else{
                        $stockButtonArr     = [0,1];//其它权限
                    }

                    $result     = [
                        'message' => '登录成功',
                        'user_id' => 0,
                        'token' => $token,
                        'nodes' => $nodes,
                        'ios_nodes' => $iosNodes,
                        'stock_button_arr' => $stockButtonArr,
                        'badge' => $messageCount,
                    ];
                    return $result;
                } else {
                    xThrow( ERR_UNKNOWN );
                }
            } else {
                xThrow( LOGIN_PASSWORE_ERROE );
            }
        }
    }
    //退出
    public function logout()
    {
        $userId                 = Func::getHeaderValueByName( 'userid' );
        if( !$userId ){
            xThrow( ERR_PARAMETER );
        } else {
            $tokenData         = [ 'user_id'=>$userId, 'is_login'=>0 ];
            $saveResult        = UserToken::saveOneData( $tokenData );
            if( $saveResult ){
                $result         = ['message'=>'退出成功'];
                return $result;
            } else {
                xThrow( LOGOUT_ERROR );
            }
        }
    }

    //找回密码,设置密码
    public function setPassword()
    {
        $mobile                 = request('mobile');
        $password               = request('password');
//        $code                   = request('code');
        if( !$mobile || !$password ){
            xThrow( ERR_PARAMETER );
        }

//        $codeResult            = Sms::checkCode( $mobile, $code );
//        if( !$codeResult ){
//            xThrow( 300001 );
//        }

        $where                  = ['mobile'=>$mobile];
        $info                   = User::getInfo( $where );
        if( $info ){
            $salt               = mt_rand( 1000, 9999 );
            $password_md5       = User::passwordMd5( $password, $salt );
            $user_data          = [ 'password'=>$password_md5, 'salt'=>$salt ];
            $update_result      = User::updateOneData( $where, $user_data );
            if( $update_result ){
                $result         = ['message'=>'密码修改成功'];
                return $result;
            } else {
                xThrow( ERR_CLIENT_USER_SET_PASSWORD_ERROE );
            }
        } else {
            xThrow( ERR_CLIENT_USER_NOT_EXIST );
        }
    }


    //通过老密码 修改密码
    public function setPasswordByOldPassword(){
        $userId            = Func::getHeaderValueByName( 'userid');
        if(!$userId ){
            xThrow( ERR_PARAMETER );
        }

        $NewPassword               = request('new_password');
        $ConfirmPassword           = request('confirm_password');
        $OldPassword               = request('old_password');

        //验证新密码是否可用
        if(strlen($NewPassword)<6 || strlen($NewPassword)>20){
            xThrow( ERR_PASSWORD_FORMAT_ERROR );
        }

        if($NewPassword!=$ConfirmPassword){
            xThrow( ERR_TWO_PASSWORD_IS_INCONSISTENT );
        }

        //获得用户信息
        $where                  = ['id'=>$userId];
        $info                   = User::getInfo($where);
        if($info){
            $OldPassword = User::passwordMd5($OldPassword,$info['salt']);
            if($OldPassword != $info['password']){
                xThrow( ERR_CLIENT_USER_AUTH_INFO );
            }
            //更新密码
            $salt               = mt_rand( 1000, 9999 );
            $password_md5       = User::passwordMd5($NewPassword,$salt);
            $user_data          = [ 'password'=>$password_md5, 'salt'=>$salt ];
            $update_result      = User::updateOneData( $where, $user_data );
            if( $update_result ){
                $result         = ['message'=>'密码修改成功'];
                return $result;
            } else {
                xThrow( ERR_CLIENT_USER_SET_PASSWORD_ERROE );
            }
        } else {
            xThrow( ERR_CLIENT_USER_AUTH_INFO );
        }
    }


    //发送短信
    public function sendSms()
    {
        $mobile                 = request('mobile');
        $type                   = request('type');
        if( !$mobile || !$type){
            xThrow( ERR_PARAMETER );
        }

        $mobileSize            =  mb_strlen( $mobile );
        if( $mobileSize != 11 ){
            xThrow(MOBILE_NUMBER_ERROR);
        }
        $mobilePreg            = '/^((1[3,5,8][0-9])|(14[5,7])|(17[0,6,7,8])|(19[7]))\d{8}$/';
        $mobilePregResult     = preg_match( $mobilePreg, $mobile );
        if( !$mobilePregResult ){
            xThrow(MOBILE_PREG_ERROR);
        }

        $where                  = ['mobile'=>$mobile];
        $mobileIsExist        = User::getInfo( $where );
        $type_result            = false;
        //type 1 注册 2找回密码 3修改密码 4修改手机号
        switch( $type ){
            case 4:
            case 1:
                if( $mobileIsExist ){
                    xThrow( MOBILE_EXIST );
                }
                break;
            case 3:
            case 2:
                if( !$mobileIsExist ){
                    xThrow( MOBILE_NOT_EXIST );
                }
                break;
            default:
                xThrow( ERR_PARAMETER );
        }
        $limitTime             = 60;//单位秒
        $is_send                = Sms::isSend( $mobile, $limitTime);
        if ($is_send) {
            xThrow( SMS_IS_SEND );
        } else {
            $code               = mt_rand(1000, 9999);
            // 暂时把发送短信关闭
            //$sendResult = true;
            $smsService         = new ZhaoyongService();
            $sendResult        = $smsService->sendSms( $mobile, $code, $type );
            $smsData = ['type' => $type, 'mobile' => $mobile, 'code' => $code];
            $insertResult = Sms::insertOneData($smsData);
            if ($sendResult && $insertResult) {
                $result = ['message'=>'短信发送成功'];
                return $result;
            } else {
                xThrow( SMS_SEND_ERROR );
            }
        }
    }
    public function checkCode(){

        $mobile                 = request('mobile');
        $code                   = request('code');
        $type                   = request('type');
        $codeResult            = Sms::checkCode( $mobile, $code, $type );
        if( !$codeResult ){
            xThrow( SMS_CODE_ERROR );
        }
        $result                 = ['message'=>'验证码正确'];
        return $result;
    }
    public function token(){
        xThrow( ERR_AUTH );
    }
    public function company(){

        $userId            = Func::getHeaderValueByName( 'userid' );
        $lists              = DepartmentUser::getCompanyListByUserId($userId);
        $result             = [ 'message'=>'请求成功', 'lists'=>$lists ];
        return $result;
    }

}